<template>
  <div class="clients-page">
    <div class="page-header">
      <h1>客户管理</h1>
      <p class="subtitle">管理客户信息，包括添加、编辑和删除操作</p>
    </div>

    <!-- 操作栏 -->
    <div class="toolbar">
      <div class="search-section">
        <el-input
          v-model="searchQuery"
          placeholder="搜索客户编码或名称..."
          style="width: 300px"
          clearable
          @input="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        
      </div>
      
      <div class="action-section">
        <el-button type="primary" @click="showCreateDialog">
          <el-icon><Plus /></el-icon>
          添加客户
        </el-button>
        <el-button @click="refreshData">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 数据表格 -->
    <el-card shadow="never">
      <el-table
        v-loading="loading"
        :data="clients"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="clientCode" label="客户编码" width="120" />
        <el-table-column prop="clientName" label="客户名称" width="200" />
        <el-table-column prop="marketType" label="市场类型" width="100" />
        <el-table-column prop="terminalType" label="终端类型" width="120" />
        <el-table-column label="分配经理" width="150">
          <template #default="{ row }">
            <div v-if="row.managerAssignments && row.managerAssignments.length > 0">
              <el-tag 
                v-for="assignment in row.managerAssignments" 
                :key="assignment.manager.id"
                size="small"
                style="margin-right: 4px; margin-bottom: 4px;"
              >
                {{ assignment.manager.fullName }}
              </el-tag>
            </div>
            <span v-else class="text-gray-400">未分配</span>
          </template>
        </el-table-column>
        <el-table-column label="工作日志" width="100">
          <template #default="{ row }">
            {{ row._count?.workLogs || 0 }}
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="{ row }">
            <div class="button-group">
              <el-button 
                type="primary" 
                size="small" 
                @click="showEditDialog(row)"
                :icon="Edit"
              >
                编辑
              </el-button>
              <el-button 
                type="success" 
                size="small" 
                @click="showAssignDialog(row)"
                :icon="User"
              >
                分配经理
              </el-button>
              <el-button 
                type="danger" 
                size="small" 
                @click="handleDelete(row)"
                :icon="Delete"
              >
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 创建/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑客户' : '添加客户'"
      width="500px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="客户编码" prop="clientCode">
          <el-input v-model="form.clientCode" placeholder="请输入客户编码" />
        </el-form-item>
        <el-form-item label="客户名称" prop="clientName">
          <el-input v-model="form.clientName" placeholder="请输入客户名称" />
        </el-form-item>
        <el-form-item label="市场类型" prop="marketType">
          <el-select v-model="form.marketType" placeholder="请选择市场类型">
            <el-option label="城网" value="城网" />
            <el-option label="农网" value="农网" />
          </el-select>
        </el-form-item>
        <el-form-item label="终端类型" prop="terminalType">
          <el-select v-model="form.terminalType" placeholder="请选择终端类型">
            <el-option label="普通终端" value="普通终端" />
            <el-option label="一般现代终端" value="一般现代终端" />
            <el-option label="加盟终端" value="加盟终端" />
            <el-option label="直营终端" value="直营终端" />
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">
            {{ isEdit ? '更新' : '创建' }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 分配经理对话框 -->
    <el-dialog
      v-model="assignDialogVisible"
      title="分配客户经理"
      width="600px"
      @close="resetAssignForm"
    >
      <div v-if="selectedClient">
        <p><strong>客户：</strong>{{ selectedClient.clientName }} ({{ selectedClient.clientCode }})</p>
        
        <div style="margin: 20px 0;">
          <h4>当前分配的经理：</h4>
          <div v-if="selectedClient.managerAssignments && selectedClient.managerAssignments.length > 0">
            <el-tag 
              v-for="assignment in selectedClient.managerAssignments" 
              :key="assignment.manager.id"
              closable
              @close="handleUnassignManager(assignment.manager.id)"
              style="margin-right: 8px; margin-bottom: 8px;"
            >
              {{ assignment.manager.fullName }} ({{ assignment.manager.username }})
            </el-tag>
          </div>
          <p v-else class="text-gray-400">暂无分配的经理</p>
        </div>

        <div>
          <h4>分配新经理：</h4>
          <el-select 
            v-model="selectedManagerId" 
            placeholder="选择客户经理"
            style="width: 100%"
            filterable
          >
            <el-option
              v-for="manager in availableManagers"
              :key="manager.id"
              :label="`${manager.fullName} (${manager.username})`"
              :value="manager.id"
            />
          </el-select>
          <el-button 
            type="primary" 
            @click="handleAssignManager"
            :disabled="!selectedManagerId"
            style="margin-top: 10px;"
          >
            分配
          </el-button>
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="assignDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue';
import {
  Search,
  Plus,
  Refresh,
  Edit,
  User,
  Delete
} from '@element-plus/icons-vue';
import { trpc } from '@/utils/trpc';
import { Message, MessageBox } from '@/utils/message';

// 响应式数据
const loading = ref(false);
const submitting = ref(false);
const clients = ref<any[]>([]);
const managers = ref<any[]>([]);
const searchQuery = ref('');
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 对话框状态
const dialogVisible = ref(false);
const assignDialogVisible = ref(false);
const isEdit = ref(false);
const selectedClient = ref<any>(null);
const selectedManagerId = ref<number | null>(null);

// 表单数据
const form = reactive({
  id: 0,
  clientCode: '',
  clientName: '',
  marketType: '',
  terminalType: '',
});

// 表单引用
const formRef = ref();

// 表单验证规则
const rules = {
  clientCode: [
    { required: true, message: '请输入客户编码', trigger: 'blur' },
    { min: 1, max: 12, message: '客户编码长度为1-12个字符', trigger: 'blur' }
  ],
  clientName: [
    { required: true, message: '请输入客户名称', trigger: 'blur' },
    { min: 1, max: 100, message: '客户名称长度为1-100个字符', trigger: 'blur' }
  ],
  marketType: [
    { required: true, message: '请选择市场类型', trigger: 'change' }
  ],
  terminalType: [
    { required: true, message: '请选择终端类型', trigger: 'change' }
  ],
};

// 计算属性
const availableManagers = computed(() => {
  if (!selectedClient.value) return managers.value;
  
  const assignedManagerIds = selectedClient.value.managerAssignments?.map((a: any) => a.manager.id) || [];
  return managers.value.filter(manager => !assignedManagerIds.includes(manager.id));
});

// 格式化日期
const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleString('zh-CN');
};

// 加载客户列表
const loadClients = async () => {
  try {
    loading.value = true;
    const response = await trpc.client.list.query({
      page: currentPage.value,
      pageSize: pageSize.value,
      search: searchQuery.value || undefined,
    });
    
    if (response.success) {
      clients.value = response.data.data;
      total.value = response.data.pagination.total;
    } else {
      Message.error(response.message || '加载客户列表失败');
    }
  } catch (error) {
    console.error('加载客户列表失败:', error);
    Message.error('加载客户列表失败');
  } finally {
    loading.value = false;
  }
};

// 加载客户经理列表
const loadManagers = async () => {
  try {
    const response = await trpc.manager.list.query({
      page: 1,
      pageSize: 100, // 后端限制最大为100
    });

    if (response.success) {
      managers.value = response.data.data;
    }
  } catch (error) {
    console.error('加载客户经理列表失败:', error);
  }
};

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1;
  loadClients();
};

// 刷新数据
const refreshData = () => {
  loadClients();
  loadManagers();
};

// 分页处理
const handleSizeChange = (size: number) => {
  pageSize.value = size;
  currentPage.value = 1;
  loadClients();
};

const handleCurrentChange = (page: number) => {
  currentPage.value = page;
  loadClients();
};

// 显示创建对话框
const showCreateDialog = () => {
  isEdit.value = false;
  dialogVisible.value = true;
};

// 显示编辑对话框
const showEditDialog = (client: any) => {
  isEdit.value = true;
  form.id = client.id;
  form.clientCode = client.clientCode;
  form.clientName = client.clientName;
  form.marketType = client.marketType;
  form.terminalType = client.terminalType;
  dialogVisible.value = true;
};

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  form.id = 0;
  form.clientCode = '';
  form.clientName = '';
  form.marketType = '';
  form.terminalType = '';
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;
  
  try {
    await formRef.value.validate();
    submitting.value = true;
    
    let response;
    if (isEdit.value) {
      response = await trpc.client.update.mutate({
        id: form.id,
        clientCode: form.clientCode,
        clientName: form.clientName,
        marketType: form.marketType as any,
        terminalType: form.terminalType as any,
      });
    } else {
      response = await trpc.client.create.mutate({
        clientCode: form.clientCode,
        clientName: form.clientName,
        marketType: form.marketType as any,
        terminalType: form.terminalType as any,
      });
    }
    
    if (response.success) {
      Message.success(response.message || (isEdit.value ? '更新成功' : '创建成功'));
      dialogVisible.value = false;
      loadClients();
    } else {
      Message.error(response.message || (isEdit.value ? '更新失败' : '创建失败'));
    }
  } catch (error) {
    console.error('提交失败:', error);
    Message.error('提交失败');
  } finally {
    submitting.value = false;
  }
};

// 删除客户
const handleDelete = async (client: any) => {
  try {
    await MessageBox.confirm(
      `确定要永久删除客户 "${client.clientName}" 吗？此操作将级联删除相关的分配关系和工作日志，且不可恢复！`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );

    const response = await trpc.client.delete.mutate({ id: client.id });

    if (response.success) {
      Message.success('删除成功');
      loadClients();
    } else {
      Message.error(response.message || '删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error);
      Message.error('删除失败');
    }
  }
};

// 显示分配对话框
const showAssignDialog = (client: any) => {
  selectedClient.value = client;
  selectedManagerId.value = null;
  assignDialogVisible.value = true;
};

// 重置分配表单
const resetAssignForm = () => {
  selectedClient.value = null;
  selectedManagerId.value = null;
};

// 分配经理
const handleAssignManager = async () => {
  if (!selectedClient.value || !selectedManagerId.value) return;
  
  try {
    const response = await trpc.client.assignManager.mutate({
      clientId: selectedClient.value.id,
      managerId: selectedManagerId.value,
    });
    
    if (response.success) {
      Message.success('分配成功');
      selectedManagerId.value = null;
      loadClients();
      // 更新当前选中的客户信息
      const updatedClient = clients.value.find(c => c.id === selectedClient.value.id);
      if (updatedClient) {
        selectedClient.value = updatedClient;
      }
    } else {
      Message.error(response.message || '分配失败');
    }
  } catch (error) {
    console.error('分配失败:', error);
    Message.error('分配失败');
  }
};

// 取消分配经理
const handleUnassignManager = async (managerId: number) => {
  if (!selectedClient.value) return;
  
  try {
    await MessageBox.confirm('确定要取消此经理的分配吗？', '确认取消', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    });

    const response = await trpc.client.unassignManager.mutate({
      clientId: selectedClient.value.id,
      managerId: managerId,
    });

    if (response.success) {
      Message.success('取消分配成功');
      loadClients();
      // 更新当前选中的客户信息
      const updatedClient = clients.value.find(c => c.id === selectedClient.value.id);
      if (updatedClient) {
        selectedClient.value = updatedClient;
      }
    } else {
      Message.error(response.message || '取消分配失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消分配失败:', error);
      Message.error('取消分配失败');
    }
  }
};

// 组件挂载时加载数据
onMounted(() => {
  loadClients();
  loadManagers();
});
</script>

<style scoped>
.clients-page {
  padding: 20px;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #1f2937;
}

.subtitle {
  margin: 0;
  color: #6b7280;
  font-size: 14px;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding: 16px;
  background: #f9fafb;
  border-radius: 8px;
}

.search-section {
  display: flex;
  align-items: center;
}

.action-section {
  display: flex;
  gap: 8px;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.text-gray-400 {
  color: #9ca3af;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}

/* 自定义 MessageBox 样式 */
:deep(.custom-message-box) {
  z-index: 9999 !important;
}

:deep(.el-message-box) {
  z-index: 9999 !important;
}

:deep(.el-overlay) {
  z-index: 9998 !important;
}

/* 按钮组样式 */
.button-group {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
  justify-content: flex-start;
  align-items: center;
}

.button-group .el-button {
  margin: 0;
  border-radius: 6px;
  font-weight: 500;
  transition: all 0.2s ease;
}

.button-group .el-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

.button-group .el-button--small {
  padding: 6px 12px;
  font-size: 12px;
}

/* 按钮特定样式 */
.button-group .el-button--success {
  background-color: #67c23a;
  border-color: #67c23a;
}

.button-group .el-button--success:hover {
  background-color: #85ce61;
  border-color: #85ce61;
}
</style>
